<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
        <el-menu-item index="my" >我的</el-menu-item>
        <el-menu-item index="department" v-if="departmentSaleDeliverData">部门</el-menu-item>
        <el-menu-item index="all" v-if="allSaleDeliverData">全部</el-menu-item>
    </el-menu>

    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="订单编号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="发货日期：">
          <el-date-picker
            v-model="listQuery.planDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称：">
              <el-autocomplete
                      clearable
                      class="inline-input"
                      value-key="customerName"
                      :fetch-suggestions="querySearch"
                      v-model="listQuery.customerName"
                      placeholder="请输入内容"
                      @select="handleSelectCustomerName"
                      :trigger-on-focus="false"
              ></el-autocomplete>
        </el-form-item>

        <el-form-item label="客户编码：">
           <el-input  v-model="listQuery.customerNumber" clearable></el-input>
        </el-form-item>

        <el-form-item label="商品信息：">
          <el-input v-model="listQuery.goodsSn" clearable></el-input>
        </el-form-item>

        <el-form-item label="业务员：" v-if="listQuery.type!='my'">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>

      <el-radio-group v-model="listQuery.sendType" size="small" @change="handleSearchList">
        <el-radio-button label="自提">自提</el-radio-button>
        <el-radio-button label="送到">送到</el-radio-button>
      </el-radio-group>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
              v-loading="listLoading"
              :data="tableData"
              border
              style="width: 100%; margin-top: 20px">
        <el-table-column  label="排货编号" min-width="150" align="center" prop="billSn">
        </el-table-column>
        <el-table-column  label="客户名称" min-width="200" align="center">
          <template slot-scope="scope">
            <div>
              {{scope.row.customerNumber}}
            </div>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>
        <el-table-column  label="发货时间" min-width="150" align="center" prop="createdAt">
        </el-table-column>
        <el-table-column  label="订单编号" min-width="150" align="center" class-name="cspantd">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.billGoodsList" :style="{'border-bottom': index==scope.row.billGoodsList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
                {{item.saleOrderSn}}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="商品信息" min-width="150"  align="center" class-name="cspantd">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.billGoodsList" :style="{'border-bottom': index==scope.row.billGoodsList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.goodsName}}/{{item.goodsSn}}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="发货数量" min-width="100" align="center" class-name="cspantd">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.billGoodsList" :style="{'border-bottom': index==scope.row.billGoodsList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.planNum}}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="发货仓库" min-width="140" align="center">
          <template slot-scope="scope">
              {{scope.row.takeWarehouse}}
          </template>
        </el-table-column>

        <el-table-column
              label="司机姓名"
              min-width="100"
              align="center">
        <template slot-scope="scope">
          {{scope.row.driverName}}
        </template>
      </el-table-column>
        <el-table-column
                label="司机手机"
                min-width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.driverMobile}}
          </template>
        </el-table-column>
        <el-table-column
                label="车牌号"
                min-width="120"
                align="center">
          <template slot-scope="scope">
              {{scope.row.driverTruckNo}}
          </template>
        </el-table-column>

        <el-table-column
                width="100"
                fixed="right"
                label="操作"
                align="center">
          <template slot-scope="scope">
            <el-button
                    v-if="listQuery.sendType == '送到'"
                    type="text"
                    size="mini"
                    @click="showPrint(scope.row)">打印发货单
            </el-button>
            <el-button
              v-if="listQuery.sendType == '自提'"
              type="text"
              size="mini"
              @click="showPrint(scope.row)">打印提货单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
      </el-pagination>
    </div>
    <!--打印弹窗-->
    <el-dialog
            :close-on-click-modal="false"
            :beforeClose="closePrint"
            :visible.sync="dialogVisible"
            width="980px">
      <div id="print-div" v-loading="loading">
        <img :src="printSrc" v-if="printSrc"/>

      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" style="width:150px;" @click="printdiv">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {getCustomerOption,getOrderUsersList,planList,getShipmentImage,getSalePrintImage} from '@/api/partner'
  import {getPrintImage} from '@/api/order'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import "@/utils/jQuery.print"
  import { mapGetters } from 'vuex'
  const defaultListQuery={
    "pageNum": 1,
    "pageSize": 10,
    "tab": "my", //all-全部，department-部门，my-我的
    "sendType": "自提", //自提/送到
    "userId": "", //业务员ID
    "customerName": "", //客户名称
    "customerNumber": "", //客户编码
    "planDate": [], //排货日期
    "goodsSn": "", //商品牌号
    "orderSn": "", //订单编码
  };
  const defaultSendForm={
    deliverId: '',
    goodsReceipt: [],
    goodsReceiptRemark: '',
    goodsReceiptDate:''
  };
  export default {
    name: "saleDeliverData",
    data(){
      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        count: 0,
        listLoading: false,
        roles:store.getters.roles ? store.getters.roles : [],
        userOptionList:[],
        dialogVisible:false,
        loading:false,
        printSrc:''
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId'
      ]),
      departmentSaleDeliverData(){
        if(this.roles.indexOf("departmentSaleDeliverData") != -1){
          return true
        }else{
          return false
        }
      },
      allSaleDeliverData(){
        if(this.roles.indexOf("allSaleDeliverData") != -1){
          return true
        }else{
          return false
        }
      },
    },
    created() {
      if(this.$route.query.tab){
        this.listQuery.tab = this.$route.query.tab
      }
      if(this.$route.query.sendType){
        this.listQuery.sendType = this.$route.query.sendType
      }
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
      this.listQuery.planDate = [startDate, endDate];
      this.getList();
      this.getUserOptionList();
    },
    filters: {

    },
    components : {
      // trajectoryMap:trajectoryMap
    },
    methods:{
      //去详情页
      toOrderDetail(type,item){
        let routeData = this.$router.resolve({name:'saleDetail',query:{id:item.orderId,type:type}});
        window.open(routeData.href);
        // this.$router.push({name:'saleDetail',query:{id:item.orderId,type:type}})
      },
      //显示打印弹窗
      showPrint(item){
        this.dialogVisible = true;
        this.printSrc = ''
        let fn = getShipmentImage
        if(this.listQuery.sendType == '自提'){
          fn = getSalePrintImage
        }
        this.loading = true
        fn({billId:item.billId}).then((res)=>{
          this.printSrc = res;
          this.loading = false
        }).catch(()=>{
          this.loading = false
        })

      },
      //关闭打印弹窗
      closePrint(){
        this.dialogVisible = false;
      },

      //打印
      printdiv(){
        $("#print-div").print({
          globalStyles:true,//是否包含父文档的样式，默认为true
          mediaPrint:true,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
          stylesheet:null,//外部样式表的URL地址，默认为null
          noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
          iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
          append:null,//将内容添加到打印内容的后面
          prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
          deferred: $.Deferred()//回调函数
        });
      },

      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList({status:1}).then((res)=>{
          this.userOptionList = res;
        })
      },

      //客户名称输入匹配
      querySearch(queryString, cb){
        getCustomerOption({keywords:queryString}).then((res)=>{
          cb(res);
        })
      },


      //选择客户名称
      handleSelectCustomerName(item){
        this.listQuery.customerName = item.customerName
      },

      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery = JSON.parse(JSON.stringify(defaultListQuery)),
        this.listQuery.tab = key;
        let now = new Date();
        let nowMonth = now.getMonth(); //当前月
        let nowYear = now.getFullYear(); //当前年
        //本月的开始时间
        let monthStartDate = new Date(nowYear, nowMonth, 1);
        //本月的结束时间
        let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
        let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
        let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
        this.listQuery.planDate = [startDate, endDate];
        this.handleSearchList();
      },
      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

      //获取列表
      getList() {
        this.listLoading = true;
        planList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },
    },
  }
</script>

<style lang="scss">
  .cspantd{
    padding:0 !important;
    .cell{
      padding:0 !important;
      .tdDiv{
        padding:5px 10px;
        min-height: 20px;
        line-height: 20px;
        box-sizing: content-box;
      }
    }
  }
  .price-block{
    font-size:12px;
    line-height:30px;
    .lab{
      display: inline-block;
      width:100px;
      text-align: right;
    }
    .text{
      display: inline-block;
    }
  }
  #print-div{
    font-size:14px !important;
    font-family: "Microsoft YaHei";
    color:#000;
    .title{
      font-size:28px;
      font-weight: bold;
      text-align: center;
      line-height: 40px;
    }
    .paper-top{
      margin-top:20px;
      line-height: 20px !important;
    }
    .good-table{
      margin-top:0px;
      table{
        border-left:1px solid #000;
        border-bottom:1px solid #000;
        td,th{
          font-weight: normal;
          border-right:1px solid #000;
          border-top:1px solid #000;
          padding:5px 10px;
          line-height: 20px;
        }
      }
    }
    .paper-bottom{
      margin-top:0px;
      line-height: 20px;
    }
  }
</style>
